package com.zz.mybatis.binding;

import cn.hutool.core.lang.ClassScanner;
import com.zz.mybatis.session.SqlSession;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author ZHOUZHEN
 * @date 2023/7/7
 */

public class MapperRegistry {

    private final Map<Class<?>,MapperProxyFactory<?>> knownMappers = new HashMap<>();

    public <T> T getMapper(Class<T> clazz, SqlSession sqlSession){
        MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>)knownMappers.get(clazz);
        if (mapperProxyFactory == null) {
            throw new RuntimeException("Type " + clazz + " is not known to the MapperRegistry.");
        }
        try {
            return mapperProxyFactory.newInstance(sqlSession);
        }catch (Exception e){
            throw new RuntimeException("Error getting mapper instance. Cause: " + e, e);
        }
    }

    public <T> void addMapper(Class<T> clazz){
        if (clazz.isInterface()) {
            if (hasMapper(clazz)){
                throw new RuntimeException("重复添加异常");
            }
            knownMappers.put(clazz,new MapperProxyFactory<>(clazz));
        }
    }

    public void addMappers(String packageName){
        Set<Class<?>> mapperSet = ClassScanner.scanPackage();
        for (Class<?> mapperClass : mapperSet) {
            addMapper(mapperClass);
        }

    }

    public <T> boolean hasMapper(Class<T> type) {
        return knownMappers.containsKey(type);
    }

}
